package com.zc.basic.infra.framework.interceptor;

import com.alibaba.fastjson.JSON;
import com.zc.commons.context.AuthenticationContext;
import com.zc.commons.pojo.AuthenticatedUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final String X_TOKEN = "x-token";
    private static final String AUTHORIZATION = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(X_TOKEN);
        if (token == null) {
            token = request.getHeader(AUTHORIZATION);
        }

        byte[] bytes = Base64.getDecoder().decode(token.getBytes("utf-8"));
        String str = new String(bytes, "utf-8");
        AuthenticatedUser authenticatedUser = JSON.parseObject(str, AuthenticatedUser.class);

        AuthenticationContext.setContextUser(authenticatedUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthenticationContext.clear();
    }
}
